<template>
  <div>
    <template v-if="showOption">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item :label="$t('shift_name')" prop="shiftName">
          <el-input v-model="queryParams.shiftName" :placeholder="$t('please_enter', { name: $t('shift_name') })"
            :show-word-limit="true" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="所属雇主" prop="employerId">
          <employerSelect
            v-model="queryParams.employerId"
            @setEmployerAllList="setEmployerAllList"
          ></employerSelect>
        </el-form-item> -->
        <el-form-item :label="$t('publisher')" prop="createBy">
          <el-input v-model="queryParams.createBy" :placeholder="$t('please_enter', { name: $t('publisher') })"
            :show-word-limit="true" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search")
            }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
      $t("reset")
    }}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['checkWork:scheduling:schedulingSetting:add']">{{ $t("add_new_shift") }}</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </template>

    <el-table ref="multipleTable" v-loading="loading" :data="classesList" row-key="id"
      @cell-click="handleSelectionChange" border :max-height="tableHeight">
      <!-- <el-table-column
        type="selection"
        width="55"
        align="center"
        :reserve-selection="true"
        v-if="isSelect"
      /> -->
      <el-table-column :label="$t('shift_name')" align="center" prop="shiftName" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('start_and_end_time')" align="center" prop="officeHours" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.workTimeStart }} - {{ scope.row.workTimeEnd }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="所属雇主"
        align="center"
        prop="employerId"
        :show-overflow-tooltip="true"
        v-if="!isSelect"
      >
        <template slot-scope="scope">
          <dict-tag :options="employerAllList" :value="scope.row.employerId" />
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('clock_in_location')" align="center" prop="clockingPlace"
        :show-overflow-tooltip="true" v-if="isSelect">
        <template slot-scope="{ row }">
          {{
      row.clockingPlace
        ? row.clockingPlace.map((item) => item.address).toString()
        : "--"
    }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('remarks')" align="center" prop="remark" :show-overflow-tooltip="true" />
      <template v-if="!isSelect">
        <el-table-column :label="$t('last_modification_time')" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{
      parseTime(
        scope.row.updateTime || scope.row.createTime,
        "{y}-{m}-{d} {h}:{i}:{s}"
      )
    }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('publisher')" align="center" prop="publisher" :show-overflow-tooltip="true" />
      </template>

      <el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width" v-if="showOption">
        <template slot-scope="scope" v-if="scope.row.shiftName != '休息'">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['checkWork:scheduling:schedulingSetting:view']">{{ $t("view") }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit"
            v-hasPermi="['checkWork:scheduling:schedulingSetting:edit']" @click="handleUpdate(scope.row)">{{
      $t("modify") }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
            v-hasPermi="['checkWork:scheduling:schedulingSetting:delete']" @click="handleDelete(scope.row)">{{
      $t("delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" :page-sizes="[10, 20, 30, 50, 100, 200]" />

    <!-- 添加或修改周期班对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px" :disabled="lookView">
        <el-form-item :label="$t('shift_name')" prop="shiftName">
          <el-input v-model="form.shiftName" :placeholder="$t('please_enter', { name: $t('shift_name') })" />
        </el-form-item>
        <el-form-item :label="$t('shift_code')" prop="shiftCode">
          <el-input v-model="form.shiftCode" :placeholder="$t('please_enter', { name: $t('shift_code') })" />
        </el-form-item>
        <el-form-item :label="$t('remarks')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('please_enter', { name: $t('remarks') })" />
        </el-form-item>
        <el-form-item :label="$t('manager')" prop="principal">
          <el-input v-model="name" :placeholder="$t('please_enter', { name: $t('manager') })" disabled />
        </el-form-item>
        <el-form-item :label="$t('shift_color')" prop="shiftColor">
          <el-color-picker v-model="form.shiftColor"></el-color-picker>
        </el-form-item>
        <el-form-item :label="$t('type')" prop="type">
          <!-- el-radio  1-工作，2-休息-->
          <el-radio-group v-model="form.type">
            <el-radio :label="1">{{ $t("work") }}</el-radio>
            <el-radio :label="2">{{ $t("rest") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('work_hours')" :prop="form.type == 1 ? 'timeRange' : ''">
          <el-time-picker is-range v-model="form.timeRange" range-separator="-" :start-placeholder="$t('start_time')"
            :end-placeholder="$t('end_time')" :placeholder="$t('please_select', { name: '' })" value-format="HH:mm" format="HH:mm"  @change="$forceUpdate()">
          </el-time-picker>
        </el-form-item>
        <el-form-item :label="$t('clock_in_deadline_time')" :prop="form.type == 1 ? 'clockInDeadline' : ''">
          <el-time-picker v-model="form.clockInDeadline" :placeholder="$t('please_select', { name: '' })"
            value-format="HH:mm" format="HH:mm">
          </el-time-picker>
        </el-form-item>
        <el-form-item :label="$t('clocking_after_work')" prop="clockInStartTime">
          <el-time-picker v-model="form.clockInStartTime" :placeholder="$t('please_select', { name: '' })"
            value-format="HH:mm" format="HH:mm">
          </el-time-picker>
        </el-form-item>
        <el-form-item :label="$t('clock_in_location')" :prop="form.type == 1 ? 'clockingPlace' : ''">

          <div class="place-item" v-for="(item, index) in form.clockingPlace" :key="index">
            <div class="place-item-left">
              <el-input v-model="item.address" readonly>
                <template slot="append">
                  <el-button type="primary" @click="selectAddress(index)">{{
      $t("select")
    }}</el-button>
                </template>
              </el-input>

              <div style="position: relative;">
                <span v-if="form.type == 1" style="color:red;position: absolute;top:10px;left:-10px">*</span>
                <el-input class="required-input" v-model="item.distance" oninput="value=value.replace(/[^\d]/g,'')"
                  style="margin: 10px 0 20px">
                  <template slot="append">{{
      $t("clock_within_meters")
    }}</template>
                </el-input>
              </div>
            </div>
            <el-button icon="el-icon-delete" circle @click="removeAddress(index)" v-if="index > 0"></el-button>
          </div>

        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addClockingPlace">{{
      $t("add_new_work_location")
    }}</el-button>
        </el-form-item>

        <el-form-item :label="$t('clock_in_method')" prop="punchingMode">
          <el-select v-model="form.punchingMode" :placeholder="$t('please_select', { name: '' })">
            <el-option label="GPS" :value="1"> </el-option>
            <el-option :label="`GPS+${$t('photograph')}`" :value="0">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('whether_allow_field_work')" prop="outwork">
          <el-radio-group v-model="form.outwork">
            <el-radio :label="1">{{ $t("yes") }}</el-radio>
            <el-radio :label="0">{{ $t("no") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('severe_late_arrival')" prop="seriouslyLate">
          <el-input v-model="form.seriouslyLate" oninput="value=value.replace(/[^\d]/g,'')">
            <template slot="append">{{ $t("minute") }}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('severe_early_leaving')" prop="seriouslyLeaveEarly">
          <el-input v-model="form.seriouslyLeaveEarly" oninput="value=value.replace(/[^\d]/g,'')">
            <template slot="append">{{ $t("minute") }}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('absenteeism')" prop="absenteeism">
          <el-input v-model="form.absenteeism"
            oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '').replace(/^0+(?!\.|$)/g, '')">
            <template slot="append">{{ $t("hour") }}</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="allowedChecked">{{
      $t("allow_late_arrival_and_early_leaving")
    }}</el-checkbox>
          <template v-if="allowedChecked">
            <el-form-item prop="notLate" style="margin-top: 10px">
              <el-input v-model="form.notLate" oninput="value=value.replace(/[^\d]/g,'')">
                <template slot="append">{{
      $t("x_minutes_not_counted_as_late_arrival")
    }}</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="notLeaveEarly" style="margin-top: 10px">
              <el-input v-model="form.notLeaveEarly" oninput="value=value.replace(/[^\d]/g,'')">
                <template slot="append">{{
      $t("x_minutes_not_counted_as_early_leaving")
    }}</template>
              </el-input>
            </el-form-item>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!lookView">
        <el-button type="primary" @click="submitForm">{{
      $t("confirm")
    }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <mapPosition :positionDialog.sync="positionDialog" @selPosition="setPostion" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  listClasses,
  getClasses,
  delClasses,
  addClasses,
  updateClasses,
} from "@/api/checkWork/classes.js";

import mapPosition from "@/components/position/map";
import employerSelect from "@/views/components/custom/employerSelect.vue";
export default {
  name: "Classes",
  components: {
    mapPosition,
    employerSelect,
  },
  props: {
    showOption: {
      type: Boolean,
      default: true,
    },
    isSelect: {
      type: Boolean,
      default: false,
    },
    checkClassesList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班次表格数据
      classesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shiftName: null,
        employeeId: null,
        createBy: null,
      },
      // 表单参数
      form: {
        clockingPlace: [
          {
            address: null,
            latitude: null,
            longitude: null,
            distance: null,
          },

        ],
        timeRange: [],
      },
      // 表单校验
      rules: {
        shiftColor: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("shift_color") }),
            trigger: "change",

          }

        ],
        type: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("type") }),
            trigger: "change",

          }

        ],
        timeRange: [
          {
            required: true,
            // message: this.$t("cannot_empty", { name: this.$t("work_hours") }),

            validator: (rule, value, callback) => {
              console.log("🐛 ~ data ~ value:", value)
              this.$forceUpdate();
              if (!value) {
                callback(new Error(this.$t("cannot_empty", {
                  name: this.$t("work_hours"),
                })));
              }
              callback();
            },
            trigger: "blur",

          }
        ],
        clockInDeadline: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("clock_in_deadline_time"),
            }),
            trigger: "change",

          }

        ],
        // clockInStartTime: [
        //   {
        //     required: true,
        //     message: this.$t("cannot_empty", {
        //       name: this.$t("clocking_after_work"),
        //     }),
        //     trigger: "change",

        //   }

        // ],
        clockingPlace: [
          // {
          //   required: true,
          //   message: this.$t("cannot_empty", {
          //     name: this.$t("clock_in_location"),
          //   }),
          //   trigger: "change",


          // }
          {
            required: true,
            validator: (rule, value, callback) => {
              // console.log("🐛 ~ data ~ value:", value)
              if (value.length < 1) {
                callback(new Error(this.$t("cannot_empty", {
                  name: this.$t("clock_in_location"),
                })));
              } else {
                value.forEach((item) => {
                  if (!item.address) {
                    callback(new Error(this.$t("cannot_empty", {
                      name: this.$t("clock_in_location"),
                    })));
                  } else if (!item.distance) {
                    callback(new Error(this.$t("cannot_empty", {
                      name: this.$t("clock_within_meters"),
                    })));
                  }
                })
                callback();
              }
            },
            trigger: 'blur'
          }


        ],
        punchingMode: [

          {

            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("clock_in_method"),
            }),
            trigger: "change",

          }
        ],
        outwork: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("whether_allow_field_work"),
            }),
            trigger: "change",


          }
        ],






        shiftName: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("shift_name") }),
            trigger: "blur",
          },
        ],
        shiftCode: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("shift_code") }),
            trigger: "blur",
          },
        ],
      },
      allowedChecked: false,
      positionDialog: false,
      optionIndex: null,
      clockingPlace: [
        {
          address: null,
          latitude: null,
          longitude: null,
          distance: null,
        },
      ],
      lookView: false,

      employerAllList: [],

      timeRange: [],
    };
  },
  computed: {
    ...mapGetters(["name", "userId"]),
  },
  watch: {
    classesList: {
      handler(newValue) {
        if (this.checkClassesList.length && this.isSelect && newValue.length) {
          let list = [];
          this.classesList.forEach((item) => {
            this.checkClassesList.forEach((val) => {
              if (val.id === item.id) {
                list.push(item);
              }
            });
          });
          if (list.length) {
            this.$nextTick(() => {
              list.forEach((row) => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
              });
            });
          }
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询班次列表 */
    getList() {
      this.loading = true;
      listClasses(this.queryParams).then((response) => {
        this.classesList = response.data.records.map((item) => {
          return item;
        });
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shiftName: null,
        shiftCode: null,
        remark: null,
        principal: this.userId,
        shiftColor: "#1890ff",
        workTimeStart: null,
        workTimeEnd: null,
        clockInDeadline: '',
        clockInStartTime: '',
        clockingPlace: null,
        punchingMode: null,
        outwork: null,
        seriouslyLate: null,
        seriouslyLeaveEarly: null,
        absenteeism: null,
        notLate: null,
        notLeaveEarly: null,
        clockingPlace: [
          {
            address: null,
            latitude: null,
            longitude: null,
            distance: null,
          }
        ],
        timeRange:[],

      };
      this.clockingPlace = [
        {
          address: null,
          latitude: null,
          longitude: null,
          distance: null,
        },
      ];
      // this.timeRange = ["08:00", "23:00"];
      this.form.timeRange = [];
      this.lookView = false;
      this.allowedChecked = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection, row) {
      this.$emit("handleSelectionClasses", selection, row);
      return;
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getClasses(id).then((response) => {
        this.form = response.data;
        this.clockingPlace = this.form.clockingPlace;
        if (this.form.workTimeStart) {
          this.form.timeRange = [this.form.workTimeStart, this.form.workTimeEnd];
        }
        if (this.form.notLate || this.form.notLeaveEarly) {
          this.allowedChecked = true;
        }
        this.form.punchingMode = parseInt(this.form.punchingMode);
        this.open = true;
        this.title = this.$t("modify");
      });
    },
    handleView(row) {
      this.reset();
      const id = row.id;
      getClasses(id).then((response) => {
        this.form = response.data;
        this.clockingPlace = this.form.clockingPlace;
        if (this.form.workTimeStart) {
          this.form.timeRange = [this.form.workTimeStart, this.form.workTimeEnd];
        }
        if (this.form.notLate || this.form.notLeaveEarly) {
          this.allowedChecked = true;
        }
        this.form.punchingMode = parseInt(this.form.punchingMode);
        this.open = true;
        this.lookView = true;
        this.title = this.$t("view");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (this.form.timeRange && this.form.timeRange.length) {
          this.form.workTimeStart = this.form.timeRange[0];
          this.form.workTimeEnd = this.form.timeRange[1];
        } else {
          this.form.workTimeStart = '';
          this.form.workTimeEnd = '';
        }
        if (!this.allowedChecked) {
          this.form.notLate = null;
          this.form.notLeaveEarly = null;
        }
        // this.form.clockingPlace = this.clockingPlace;
        if (valid) {
          if (this.form.id != null) {
            delete this.form.createTime;
            delete this.form.updateTime;
            console.log("🐛 ~ updateClasses ~ this.form:", this.form)
            if (!this.form.clockInDeadline) this.form.clockInDeadline = '';
            if (!this.form.clockInStartTime) this.form.clockInStartTime = '';

            updateClasses(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          } else {
            addClasses(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return delClasses(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "classes/classes/export",
        {
          ...this.queryParams,
        },
        `classes_${new Date().getTime()}.xlsx`
      );
    },
    setEmployerAllList(list) {
      this.employerAllList = list.map((item) => {
        return {
          ...item,
          value: item.value.toString(),
        };
      });
    },
    selectAddress(index) {
      this.optionIndex = index;
      this.positionDialog = true;
    },
    setPostion(postion) {
      this.$set(this.form.clockingPlace, this.optionIndex, {
        ...postion,
        distance: null,
      });
    },
    addClockingPlace() {
      this.form.clockingPlace.push({
        address: null,
        latitude: null,
        longitude: null,
        distance: null,
      });
    },
    removeAddress(index) {
      this.form.clockingPlace.splice(index, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
.place-item {
  display: flex;
  align-items: center;

  &-left {
    margin-right: 20px;
  }
}

/* .required-input::before{
  content: '*';
  color:red;
} */
</style>
